package com.opages.netty.demo.netty.rpc.provider;

import com.opages.netty.demo.netty.rpc.common.RpcInvoker;
import com.opages.netty.demo.netty.rpc.common.RpcProtocol;
import com.opages.netty.demo.netty.stickybag.MessageProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @author daizhong.liu
 * @create 2021-12-14 16:27
 **/
public class ProviderHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.err.println("原始消息:"+msg.toString());
        if(msg != null && msg instanceof RpcProtocol) {
            RpcProtocol protocol = (RpcProtocol) msg;
            System.err.println(protocol.toString());

            if(RpcProtocol.HEADER_PROTOCOL.equals(new String(protocol.getHeader(),CharsetUtil.UTF_8))) {
                Object result = invoke(protocol.toInvoker());
                protocol.setResult(result.toString().getBytes());
                ctx.writeAndFlush(protocol);
            }
        }
    }

    private Object invoke(RpcInvoker invoker) {
        try {
            Method method = invoker.getMethod();
            Class<?> clazz = method.getDeclaringClass();
            Object obj = clazz.newInstance();
            Object result = method.invoke(obj, null);
            return result;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
